import sys
import time
from pinpong.extension.unihiker import *
from pinpong.board import Board, Pin, NeoPixel, IRRemote, IRRecv

class SHIELD:
    def __init__(self):
        # 初始化开发板
        Board().begin()
        
        # 初始化电机和红外引脚
        self.ir = self.IR()
        self.m1 = self.M1()
        self.m2 = self.M2()

    class IR:
        def __init__(self):
            # 固定红外发射引脚为 P15
            self.ir_sender = IRRemote(Pin(Pin.P15))
            # 固定红外接收引脚为 P14
            self.ir_receiver = IRRecv(Pin(Pin.P14), self._receive_callback)
            # 存储用户设置的回调函数
            self.user_callback = None

        def send(self, code):
            """发送红外信号，支持十进制和十六进制格式的代码"""
            # 如果传入的是字符串形式的十六进制代码，转换为整数
            if isinstance(code, str) and code.startswith('0x'):
                code = int(code, 16)
            self.ir_sender.send(code)

        def set_receive_callback(self, callback):
            """设置红外接收回调函数"""
            self.user_callback = callback

        def _receive_callback(self, data):
            """内部接收回调函数，处理原始数据并调用用户回调"""
            if self.user_callback:
                # 将原始数据转换为十六进制字符串并传递给用户回调
                hex_code = hex(data)
                self.user_callback(hex_code)


    
    class M1:
        def __init__(self):
            # 初始化M1引脚
            self.M1_veer = Pin(Pin.P5, Pin.OUT)
            self.M1_speed = Pin(Pin.P8, Pin.PWM)
            
        def run(self, direction, speed):
            self.M1_veer.write_digital(direction)
            self.M1_speed.write_analog(speed)
            
        def stop(self):
            self.M1_speed.write_analog(0)
        
    class M2:
        def __init__(self):
            # 初始化M2引脚
            self.M2_veer = Pin(Pin.P6, Pin.OUT)
            self.M2_speed = Pin(Pin.P16, Pin.PWM)
            
        def run(self, direction, speed):
            self.M2_veer.write_digital(direction)
            self.M2_speed.write_analog(speed)
            
        def stop(self):
            self.M2_speed.write_analog(0)

if __name__ == "__main__":
    shield = SHIELD()
    
    # 模拟原始代码中的控制逻辑
    shield.m1.run(1, 512)  # 前进方向，中等速度
    shield.m2.run(1, 512)
    time.sleep(5)
    
    shield.m1.stop()  # 停止M1
    time.sleep(3)
    
    shield.m1.run(0, 512)  # 后退方向，中等速度
    shield.m2.run(0, 512)
    time.sleep(5)
    
    shield.m1.stop()  # 停止M1
    time.sleep(3)